home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / json / __init__.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  11.5 KB  |  290 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''A simple, fast, extensible JSON encoder and decoder
  5.  
  6. JSON (JavaScript Object Notation) <http://json.org> is a subset of
  7. JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
  8. interchange format.
  9.  
  10. json exposes an API familiar to uses of the standard library
  11. marshal and pickle modules.
  12.  
  13. Encoding basic Python object hierarchies::
  14.  
  15.     >>> import json
  16.     >>> json.dumps([\'foo\', {\'bar\': (\'baz\', None, 1.0, 2)}])
  17.     \'["foo", {"bar": ["baz", null, 1.0, 2]}]\'
  18.     >>> print json.dumps("\\"foo\\bar")
  19.     "\\"foo\\bar"
  20.     >>> print json.dumps(u\'\\u1234\')
  21.     "\\u1234"
  22.     >>> print json.dumps(\'\\\\\')
  23.     "\\\\"
  24.     >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
  25.     {"a": 0, "b": 0, "c": 0}
  26.     >>> from StringIO import StringIO
  27.     >>> io = StringIO()
  28.     >>> json.dump([\'streaming API\'], io)
  29.     >>> io.getvalue()
  30.     \'["streaming API"]\'
  31.  
  32. Compact encoding::
  33.  
  34.     >>> import json
  35.     >>> json.dumps([1,2,3,{\'4\': 5, \'6\': 7}], separators=(\',\',\':\'))
  36.     \'[1,2,3,{"4":5,"6":7}]\'
  37.  
  38. Pretty printing (using repr() because of extraneous whitespace in the output)::
  39.  
  40.     >>> import json
  41.     >>> print repr(json.dumps({\'4\': 5, \'6\': 7}, sort_keys=True, indent=4))
  42.     \'{\\n    "4": 5, \\n    "6": 7\\n}\'
  43.  
  44. Decoding JSON::
  45.  
  46.     >>> import json
  47.     >>> json.loads(\'["foo", {"bar":["baz", null, 1.0, 2]}]\')
  48.     [u\'foo\', {u\'bar\': [u\'baz\', None, 1.0, 2]}]
  49.     >>> json.loads(\'"\\\\"foo\\\\bar"\')
  50.     u\'"foo\\x08ar\'
  51.     >>> from StringIO import StringIO
  52.     >>> io = StringIO(\'["streaming API"]\')
  53.     >>> json.load(io)
  54.     [u\'streaming API\']
  55.  
  56. Specializing JSON object decoding::
  57.  
  58.     >>> import json
  59.     >>> def as_complex(dct):
  60.     ...     if \'__complex__\' in dct:
  61.     ...         return complex(dct[\'real\'], dct[\'imag\'])
  62.     ...     return dct
  63.     ...
  64.     >>> json.loads(\'{"__complex__": true, "real": 1, "imag": 2}\',
  65.     ...     object_hook=as_complex)
  66.     (1+2j)
  67.     >>> import decimal
  68.     >>> json.loads(\'1.1\', parse_float=decimal.Decimal)
  69.     Decimal(\'1.1\')
  70.  
  71. Extending JSONEncoder::
  72.  
  73.     >>> import json
  74.     >>> class ComplexEncoder(json.JSONEncoder):
  75.     ...     def default(self, obj):
  76.     ...         if isinstance(obj, complex):
  77.     ...             return [obj.real, obj.imag]
  78.     ...         return json.JSONEncoder.default(self, obj)
  79.     ...
  80.     >>> dumps(2 + 1j, cls=ComplexEncoder)
  81.     \'[2.0, 1.0]\'
  82.     >>> ComplexEncoder().encode(2 + 1j)
  83.     \'[2.0, 1.0]\'
  84.     >>> list(ComplexEncoder().iterencode(2 + 1j))
  85.     [\'[\', \'2.0\', \', \', \'1.0\', \']\']
  86.  
  87.  
  88. Using json.tool from the shell to validate and
  89. pretty-print::
  90.  
  91.     $ echo \'{"json":"obj"}\' | python -mjson.tool
  92.     {
  93.         "json": "obj"
  94.     }
  95.     $ echo \'{ 1.2:3.4}\' | python -mjson.tool
  96.     Expecting property name: line 1 column 2 (char 2)
  97.  
  98. Note that the JSON produced by this module\'s default settings
  99. is a subset of YAML, so it may be used as a serializer for that as well.
  100.  
  101. '''
  102. __version__ = '1.9'
  103. __all__ = [
  104.     'dump',
  105.     'dumps',
  106.     'load',
  107.     'loads',
  108.     'JSONDecoder',
  109.     'JSONEncoder']
  110. __author__ = 'Bob Ippolito <bob@redivi.com>'
  111. from decoder import JSONDecoder
  112. from encoder import JSONEncoder
  113. _default_encoder = JSONEncoder(skipkeys = False, ensure_ascii = True, check_circular = True, allow_nan = True, indent = None, separators = None, encoding = 'utf-8', default = None)
  114.  
  115. def dump(obj, fp, skipkeys = False, ensure_ascii = True, check_circular = True, allow_nan = True, cls = None, indent = None, separators = None, encoding = 'utf-8', default = None, **kw):
  116.     """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
  117.     ``.write()``-supporting file-like object).
  118.  
  119.     If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
  120.     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
  121.     will be skipped instead of raising a ``TypeError``.
  122.  
  123.     If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
  124.     may be ``unicode`` instances, subject to normal Python ``str`` to
  125.     ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
  126.     understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
  127.     to cause an error.
  128.  
  129.     If ``check_circular`` is ``False``, then the circular reference check
  130.     for container types will be skipped and a circular reference will
  131.     result in an ``OverflowError`` (or worse).
  132.  
  133.     If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
  134.     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
  135.     in strict compliance of the JSON specification, instead of using the
  136.     JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
  137.  
  138.     If ``indent`` is a non-negative integer, then JSON array elements and object
  139.     members will be pretty-printed with that indent level. An indent level
  140.     of 0 will only insert newlines. ``None`` is the most compact representation.
  141.  
  142.     If ``separators`` is an ``(item_separator, dict_separator)`` tuple
  143.     then it will be used instead of the default ``(', ', ': ')`` separators.
  144.     ``(',', ':')`` is the most compact JSON representation.
  145.  
  146.     ``encoding`` is the character encoding for str instances, default is UTF-8.
  147.  
  148.     ``default(obj)`` is a function that should return a serializable version
  149.     of obj or raise TypeError. The default simply raises TypeError.
  150.  
  151.     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
  152.     ``.default()`` method to serialize additional types), specify it with
  153.     the ``cls`` kwarg.
  154.  
  155.     """
  156.     if skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw:
  157.         iterable = _default_encoder.iterencode(obj)
  158.     elif cls is None:
  159.         cls = JSONEncoder
  160.     
  161.     iterable = cls(skipkeys = skipkeys, ensure_ascii = ensure_ascii, check_circular = check_circular, allow_nan = allow_nan, indent = indent, separators = separators, encoding = encoding, default = default, **kw).iterencode(obj)
  162.     for chunk in iterable:
  163.         fp.write(chunk)
  164.     
  165.  
  166.  
  167. def dumps(obj, skipkeys = False, ensure_ascii = True, check_circular = True, allow_nan = True, cls = None, indent = None, separators = None, encoding = 'utf-8', default = None, **kw):
  168.     """Serialize ``obj`` to a JSON formatted ``str``.
  169.  
  170.     If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
  171.     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
  172.     will be skipped instead of raising a ``TypeError``.
  173.  
  174.     If ``ensure_ascii`` is ``False``, then the return value will be a
  175.     ``unicode`` instance subject to normal Python ``str`` to ``unicode``
  176.     coercion rules instead of being escaped to an ASCII ``str``.
  177.  
  178.     If ``check_circular`` is ``False``, then the circular reference check
  179.     for container types will be skipped and a circular reference will
  180.     result in an ``OverflowError`` (or worse).
  181.  
  182.     If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
  183.     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
  184.     strict compliance of the JSON specification, instead of using the
  185.     JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
  186.  
  187.     If ``indent`` is a non-negative integer, then JSON array elements and
  188.     object members will be pretty-printed with that indent level. An indent
  189.     level of 0 will only insert newlines. ``None`` is the most compact
  190.     representation.
  191.  
  192.     If ``separators`` is an ``(item_separator, dict_separator)`` tuple
  193.     then it will be used instead of the default ``(', ', ': ')`` separators.
  194.     ``(',', ':')`` is the most compact JSON representation.
  195.  
  196.     ``encoding`` is the character encoding for str instances, default is UTF-8.
  197.  
  198.     ``default(obj)`` is a function that should return a serializable version
  199.     of obj or raise TypeError. The default simply raises TypeError.
  200.  
  201.     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
  202.     ``.default()`` method to serialize additional types), specify it with
  203.     the ``cls`` kwarg.
  204.  
  205.     """
  206.     if skipkeys is False and ensure_ascii is True and check_circular is True and allow_nan is True and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw:
  207.         return _default_encoder.encode(obj)
  208.     if cls is None:
  209.         cls = JSONEncoder
  210.     
  211.     return cls(skipkeys = skipkeys, ensure_ascii = ensure_ascii, check_circular = check_circular, allow_nan = allow_nan, indent = indent, separators = separators, encoding = encoding, default = default, **kw).encode(obj)
  212.  
  213. _default_decoder = JSONDecoder(encoding = None, object_hook = None)
  214.  
  215. def load(fp, encoding = None, cls = None, object_hook = None, parse_float = None, parse_int = None, parse_constant = None, **kw):
  216.     '''Deserialize ``fp`` (a ``.read()``-supporting file-like object
  217.     containing a JSON document) to a Python object.
  218.  
  219.     If the contents of ``fp`` is encoded with an ASCII based encoding other
  220.     than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
  221.     be specified. Encodings that are not ASCII based (such as UCS-2) are
  222.     not allowed, and should be wrapped with
  223.     ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
  224.     object and passed to ``loads()``
  225.  
  226.     ``object_hook`` is an optional function that will be called with the
  227.     result of any object literal decode (a ``dict``). The return value of
  228.     ``object_hook`` will be used instead of the ``dict``. This feature
  229.     can be used to implement custom decoders (e.g. JSON-RPC class hinting).
  230.  
  231.     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
  232.     kwarg.
  233.  
  234.     '''
  235.     return loads(fp.read(), encoding = encoding, cls = cls, object_hook = object_hook, parse_float = parse_float, parse_int = parse_int, parse_constant = parse_constant, **kw)
  236.  
  237.  
  238. def loads(s, encoding = None, cls = None, object_hook = None, parse_float = None, parse_int = None, parse_constant = None, **kw):
  239.     '''Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
  240.     document) to a Python object.
  241.  
  242.     If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
  243.     other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
  244.     must be specified. Encodings that are not ASCII based (such as UCS-2)
  245.     are not allowed and should be decoded to ``unicode`` first.
  246.  
  247.     ``object_hook`` is an optional function that will be called with the
  248.     result of any object literal decode (a ``dict``). The return value of
  249.     ``object_hook`` will be used instead of the ``dict``. This feature
  250.     can be used to implement custom decoders (e.g. JSON-RPC class hinting).
  251.  
  252.     ``parse_float``, if specified, will be called with the string
  253.     of every JSON float to be decoded. By default this is equivalent to
  254.     float(num_str). This can be used to use another datatype or parser
  255.     for JSON floats (e.g. decimal.Decimal).
  256.  
  257.     ``parse_int``, if specified, will be called with the string
  258.     of every JSON int to be decoded. By default this is equivalent to
  259.     int(num_str). This can be used to use another datatype or parser
  260.     for JSON integers (e.g. float).
  261.  
  262.     ``parse_constant``, if specified, will be called with one of the
  263.     following strings: -Infinity, Infinity, NaN, null, true, false.
  264.     This can be used to raise an exception if invalid JSON numbers
  265.     are encountered.
  266.  
  267.     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
  268.     kwarg.
  269.  
  270.     '''
  271.     if cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and not kw:
  272.         return _default_decoder.decode(s)
  273.     if cls is None:
  274.         cls = JSONDecoder
  275.     
  276.     if object_hook is not None:
  277.         kw['object_hook'] = object_hook
  278.     
  279.     if parse_float is not None:
  280.         kw['parse_float'] = parse_float
  281.     
  282.     if parse_int is not None:
  283.         kw['parse_int'] = parse_int
  284.     
  285.     if parse_constant is not None:
  286.         kw['parse_constant'] = parse_constant
  287.     
  288.     return cls(encoding = encoding, **kw).decode(s)
  289.  
  290.